package cc.zstart.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ParseUtil {

	public static Double parseDouble(String str, Double def){
		Double r = def;
		try {
			r = Double.parseDouble(str);
		} catch (Exception e) {
			r = def;
		}
		return r;
	}
	
	public static Double parseDouble(String str){
		return parseDouble(str, null);
	}
	
	public static Long parseLong(String str, Long def){
		Long r = def;
		try {
			r = Long.parseLong(str);
		} catch (Exception e) {
			r = def;
		}
		return r;
	}
	
	public static Long parseLong(String str){
		return parseLong(str, null);
	}
	
	public static Integer parseInteger(String str, Integer def){
		Integer r = def;
		try {
			r = Integer.parseInt(str);
		} catch (Exception e) {
			r = def;
		}
		return r;
	}
	
	public static Integer parseInteger(String str){
		return parseInteger(str, null);
	}
	
	public static Date parseDate(String str, String format, Date def){
		Date r = def;
		try {
			r = new SimpleDateFormat(format).parse(str);
		} catch (Exception e) {
			r = def;
		}
		return r;
	}
	
	public static Date parseDate(String str, String format){
		return parseDate(str, format, null);
	}
	
	public static Long[] parseLongArr(String str, String separator) {
		if (StringUtils.isEmpty(str)) {
			return null;
		}
		if (StringUtils.isEmpty(separator)) {
			separator = ",";
		}
		String[] arrs = str.split(separator);
		if (arrs != null && arrs.length > 0) {
			List<Long> list = new ArrayList<Long>();
			for (String s : arrs) {
				Long l = parseLong(s);
				if (l != null) {
					list.add(l);
				}
			}
			return list.toArray(new Long[list.size()]);
		} else {
			return null;
		}
	}
	public static Long[] parseLongArr(String str) {
		return parseLongArr(str, ",");
	}
	public static Integer[] parseIntegerArr(String str, String separator) {
		if (StringUtils.isEmpty(str)) {
			return null;
		}
		if (StringUtils.isEmpty(separator)) {
			separator = ",";
		}
		String[] arrs = str.split(separator);
		if (arrs != null && arrs.length > 0) {
			List<Integer> list = new ArrayList<Integer>();
			for (String s : arrs) {
				Integer l = parseInteger(s);
				if (l != null) {
					list.add(l);
				}
			}
			if(list.size() > 0){
				return list.toArray(new Integer[list.size()]);
			}
		}
		return null;
	}
	public static Integer[] parseIntegerArr(String str) {
		return parseIntegerArr(str, ",");
	}

	public static String formatDate(Date date, String format){
		return DateFormatUtils.format(date, format);
	}
}
